<?php
namespace app\repository;

use app\entity\Clazz;
use app\model\Page;
use app\Utils;
use app\repository\UserRepository;

/**
 * 对班级表实现增删改查
 * 
 * */
class ClazzRepository extends BaseRepository {
    private $table = 'clazz';
    private $where = [];

    /**
     * 大于等于入学日期
     * @param @intDate int类型的时间 20220117
     * */
    public function entranceDateGreaterThanOrEqauls($intDate) {
        if (is_int($intDate)) {
           array_push($this->where, "`clazz`.`entrance_date` >= $intDate"); 
        }
    }

    public function entranceDateLessThanOrEqauls($intDate) {
        if (is_int($intDate)) {
            array_push($this->where, "`clazz`.`entrance_date` <= $intDate"); 
        }
    }

    public function findById($id) {
        $conn = self::getConn();
        $fields = $this->getFields();
        $from = $this->getQueryFrom();
        $query = "SELECT $fields FROM $from WHERE `clazz`.`id` = $id";

        $stmt = $conn->prepare($query); 
        $stmt->execute();

        // 获取到查询到的所有记录
        $rows = $stmt->fetchAll();
        $conn = null;
        
        if (count($rows) > 0) {
            return new Clazz($rows[0]);
        } else {
            return null;
        }
    }

    function getEntity() {
        return new Clazz();
    }

    function getTable() {
        return 'clazz';
    }

    function getManyToOne() {
        return [
            'user' => new UserRepository(),
            'create_user' => new UserRepository()
        ];
    }

    private function getWhereString() {
        $i = 0;
        $result = '';
        foreach($this->where as $value) {
            if ($i !== 0) {
                $result .= ' and ';
            } else {
                $result .= ' where ';
            }
            $result .= $value;
            $i++;
        }
        return $result;
    }


    public function nameContains($name) {
        if (isset($name) && (!empty($name) || $name === '0')) {
            array_push($this->where, "`clazz`.`name` LIKE '%$name%'");
        }
    }

    /**
     * 分页 
     * @param $number 第几页
     * @param $size 每页大小
     * */
    public function page($number, $size = 10) {
        $conn = self::getConn();
        // 去判断当前用户名，密码是否与数据库当中存的一致
        $begin = $number * $size;

        // 接拼查询条件
        $where = $this->getWhereString();
        $fields = $this->getFields();
        $from = $this->getQueryFrom();
        $query = "SELECT $fields FROM $from $where order by `$this->table`.`id` desc limit $begin, $size";
        
        $stmt = $conn->prepare($query); 
        $stmt->execute();

        // 获取到查询到的所有记录
        $clazzes = $stmt->fetchAll();
        $content = [];
        foreach($clazzes as $value) {
            array_push($content, new Clazz($value));
        }
      
        // 查询一共有多少条
        $query = "select COUNT(*) FROM $from $where";
        $stmt = $conn->prepare($query); 
        $stmt->execute();
        $rows = $stmt->fetch();
        $totalCount = (int) $rows[0];

        // 查询完毕，关闭数据库连接
        $conn = null;
      
        return new Page(
            $content,
            $number,
            $size,
            $totalCount
        );
    }

    /**
     * 新建
     * @return 正确执行， true; 发生错误 -》 数据库报错信息
     * */
    public function save($clazz) {
        try {
            $conn = self::getConn();
            $clazzUserId = $clazz->user->id;
            $classCreateUserId = $clazz->createUser->id;
            $sql = "INSERT INTO `$this->table` (`name`, `entrance_date`, `user_id`, `create_user_id`, `number_of_students`) VALUES ('$clazz->name', '$clazz->entranceDate', '$clazzUserId', '$classCreateUserId', '$clazz->numberOfStudents')";
            $conn->exec($sql);           
        }
        catch(\PDOException $e)
        {
            // var_dump($e);
            return $e->getMessage();
        }
         
        $conn = null;  
        return true;
    }

    public function update($id, $name, $entranceDate, $numberOfStudents, $userId) {
        try {
            $conn = self::getConn();
            $sql = "UPDATE `clazz` SET `name`='$name', `entrance_date`='$entranceDate', `number_of_students`='$numberOfStudents', `user_id`= '$userId'
            WHERE `id` = $id";
            // 使用 exec() ，没有结果返回 
            $conn->exec($sql);
        }
        catch(\PDOException $e)
        {
            return $e->getMessage();
        }
         
        $conn = null;  
        return true;
    }

    public function userNameContains($userName) {
        if (isset($userName) && !empty($userName)) {
            array_push($this->where, "`user`.`name` LIKE '%$userName%'");
        }
    }
}